import React, { FC, useState } from 'react'
import { Button, Col, DatePicker, Form, Input, Modal, Row, Select, Spin, Tabs } from 'antd'
const { Option } = Select
import moment from 'moment';

import { useSearchTankQuery, SearchTankDocument, TankAttributesFragment, useCreateTankMutation, useUpdateTankMutation, useDeleteTankMutation, _UpdateTankInput, TankTypeAttributesFragment, useSearchTankTypeQuery } from '../__generate/graphql-frontend'
import { TankOperationList } from './TankOperationList'

const { TabPane } = Tabs

enum ShowForm {
    None,
    Create,
    Update
}

type InputParameters = Partial<_UpdateTankInput>

function mapToInput(data: TankAttributesFragment | undefined): InputParameters {

    const modifiedData = { ...data }
    delete modifiedData.__typename

    // @ts-ignore
    const result: InputParameters = { ...modifiedData }

    result.tankType = data?.tankType.id

    return result
}

export const TankTabs: FC = () => {

    const [showForm, setShowForm] = useState<ShowForm>(ShowForm.None)
    const [inputParameters, setInputParameters] = useState<InputParameters>({})

    const { data, loading, error } = useSearchTankQuery({ variables: { cond: "1==1" } })
    const tankList = data?.searchTank.elems

    const [createTankMutation, {error: errorCT}] = useCreateTankMutation()
    const [updateTankMutation] = useUpdateTankMutation()
    const [deleteTankMutation] = useDeleteTankMutation()

    const { data: dataTT, loading: loadingTT, error: errorTT } = useSearchTankTypeQuery()

    let timer: number = 0
    let searchTankTypeString: string = ""

    const changeInputParameters = (params: InputParameters) => {
        var input = { ...inputParameters }
        setInputParameters(Object.assign(input, params))
    }

    const getTabs = (list: typeof tankList) => {
        return (
            list?.map(elem => {
                return (
                    <TabPane key={elem.id ?? ""} tab={elem.id}>
                        <Row>
                            <Col span={4}>{"Tank open date: " + elem.tankOpenDate}</Col>
                            <Col span={4}>{"Current tank volume: " + elem.currentVal}</Col>
                            <Col span={8}>{"Owner: " + elem.owner.entityId}</Col>
                            <Col span={4}>{"Location coordinates: " + elem.location.latitude + ":" + elem.location.longitude}</Col>
                        </Row>
                        {/* <Button style={{ margin: "10px" }}
                            onClick={() => {
                                setInputParameters(mapToInput(elem))
                                setShowForm(ShowForm.Update)
                            }}
                        >Edit tank</Button> */}
                        <Button style={{ margin: "10px" }}
                            key={elem.id ?? ""}
                            onClick={(e) => {
                                deleteTankMutation({
                                    variables: {
                                        id: elem.id
                                    },
                                    update: (store) => {
                                        store.writeQuery({
                                            query: SearchTankDocument,
                                            variables: { cond: "1==1" },
                                            data: {
                                                searchTank: {
                                                    elems: tankList!.filter(x => x.id !== elem.id)
                                                }
                                            }
                                        })
                                    }
                                })
                            }}
                        >Delete tank</Button>
                        <p />
                        <TankOperationList tankId={elem.id} />
                    </TabPane>
                )
            })
        )
    }

    if (loading) return (<Spin tip="Loading..." />);
    if (error) return <p>`Error! ${error.message}`</p>;

    return (
        <>
            <Button style={{ margin: "20px" }}
                onClick={() => {
                    setInputParameters({})
                    setShowForm(ShowForm.Create)
                }}>
                Add new tank
            </Button>
            <Modal visible={showForm != ShowForm.None}
                onCancel={() => setShowForm(ShowForm.None)}
                onOk={() => {
                    if (showForm == ShowForm.Create) {

                        createTankMutation({
                            variables: {
                                // @ts-ignore
                                input: inputParameters
                            },
                            update: (store, result) => {
                                store.writeQuery({
                                    query: SearchTankDocument,
                                    variables: { cond: "1==1" },
                                    data: {
                                        searchTank: {
                                            elems: [, ...tankList!, result.data?.packet?.createTank]
                                        }
                                    }
                                })
                            }
                        })
                    } else if (showForm == ShowForm.Update) {
                        updateTankMutation({ variables: { input: Object.assign(inputParameters) as _UpdateTankInput } })
                    }
                    setShowForm(ShowForm.None)
                }}
            >
                <Form>
                    <Form.Item label={"TankType"}>
                        <Select
                            onChange={value => changeInputParameters({ tankType: value })}
                            value={inputParameters.tankType!}
                        >
                            {dataTT?.searchTankType?.elems?.map(d =>
                                <Option
                                    key={d.id}
                                    value={d.id}
                                >
                                    {d.name + "(" + d.minVal + "-" + d.maxVal + " "  + d.measure?.name + ")"}
                                </Option>)}
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Input placeholder="Name"
                            value={inputParameters.id!}
                            onChange={e => changeInputParameters({ id: e.target.value })}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Input placeholder="Owner"
                            value={inputParameters.owner?.entityId!}
                            onChange={e => changeInputParameters({ owner: { entityId: e.target.value } })}
                        />
                    </Form.Item>
                    <Form.Item>
                        <DatePicker placeholder="Tank Open Date"
                            //defaultValue={moment()}
                            value={inputParameters.tankOpenDate ? moment(inputParameters.tankOpenDate, "YYYY-MM-DD") : null}
                            //value={inputParameters.tankDate}
                            onChange={moment => changeInputParameters({ tankOpenDate: moment?.format("YYYY-MM-DD") })}
                            format="YYYY-MM-DD"

                        />
                    </Form.Item>
                    <Form.Item>
                        <Input placeholder="Latitude"
                            value={inputParameters.location?.latitude!}
                            onChange={e => changeInputParameters({ location: { latitude: e.target.value, longitude: inputParameters.location?.longitude } })}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Input placeholder="Logitude"
                            value={inputParameters.location?.longitude!}
                            onChange={e => changeInputParameters({ location: { latitude: inputParameters.location?.latitude, longitude: e.target.value } })}
                        />
                    </Form.Item>
                </Form>
            </Modal>
            <Form style={{ margin: "10px" }}>
                <Form.Item>
                    <Tabs>
                        {getTabs(tankList)}
                    </Tabs>
                </Form.Item>
            </Form>

        </>
    )




}

